<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-tabs tab-position="top" class="demo-tabs">
				<el-tab-pane v-for="(item, index) in areaSelectData" :key="index" :label="item.name">
					<div style="padding-left: 8px">
						<el-button type="warning" @click="callAreaLightOnOff('turn_on', item.areaId)">灯光全开</el-button>
						<el-button type="info" @click="callAreaLightOnOff('turn_off', item.areaId)">灯光全关</el-button>
					</div>
					<div style="display: flex; flex-wrap: wrap">
						<el-card v-for="(entity, entityIndex) in item.entityList" :key="entityIndex" class="box-card">
							<template #header>
								<div class="card-header">
									<span>{{ entity.customeName }}</span>
									<el-switch
										v-if="
											entity.showAs == 'switch' ||
											entity.showAs == 'light' ||
											entity.showAs == 'fan' ||
											entity.showAs == 'climate' ||
											entity.showAs == 'humidifier'
										"
										v-model="entity.switchSate"
										:disabled="entity.disabled"
										@change="(value) => callEntityOnOff(value, entity.entityId, entity.entityType)"
									/>
									<span v-if="entity.showAs == 'cover'">
										<el-button text>打开</el-button>
										<el-button text>暂停</el-button>
										<el-button text>关闭</el-button>
									</span>
								</div>
							</template>
							<div class="item">
								<span>当前状态：</span>
								<span>{{ getSateName(entity.state) }}</span>
							</div>
						</el-card>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>
	</div>
</template>

<script setup lang="ts" name="controlPanel">
import { fetchList, controlPanelList, callOnOffService } from '/@/api/homecenter/hassEntityRegistry';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { fetchSelectList } from '/@/api/homecenter/hassAreaRegistry';
import { useDict } from '/@/hooks/dict';
import mittBus from '/@/utils/mitt';
import { onMounted, onUnmounted } from 'vue';
import { json } from 'stream/consumers';

// 引入组件

// 定义查询字典
const { entity_type } = useDict('entity_type');
const { entityState } = useDict('entityState');

// 定义变量内容
const areaSelectData = ref([]) as any;
const entityList = ref([]) as any;

const getAreaList = async () => {
	fetchSelectList().then((res: any) => {
		res.data.forEach((item) => {
			item['entityList'] = [];
			areaSelectData.value.push(item);
		});
		getControlPanelList();
	});
};

const getControlPanelList = async () => {
	controlPanelList().then((res: any) => {
		res.data.forEach((item) => {
			for (let i in areaSelectData.value) {
				if (areaSelectData.value[i].areaId == item.areaId) {
					areaSelectData.value[i]['entityList'].push(item);
				}
			}
			switch (item.state) {
				case 'on':
					item['switchSate'] = true;
					break;
				case 'off':
					item['switchSate'] = false;
					break;
				case 'unavailable':
					item['switchSate'] = false;
					item['disabled'] = true;
					break;
			}
			entityList.value.push(item);
		});
	});
};

const getSateName = (value: string) => {
	for (let i in entityState.value) {
		if (entityState.value[i].value == value) {
			return entityState.value[i].label;
		}
	}
	return value;
};

const callEntityOnOff = async (value: boolean, entityId: string, entityType: string) => {
	let params = {
		domains: [entityType],
		entityIds: [entityId],
		operation: '',
	};

	if (value) {
		params.operation = 'turn_on';
	} else {
		params.operation = 'turn_off';
	}
	try {
		await callOnOffService(params);
		useMessage().success('操作成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

const callAreaLightOnOff = async (operation: string, areaId: string) => {
	let params = {
		domains: ['light'],
		areaIds: [areaId],
		operation: operation,
	};

	try {
		await callOnOffService(params);
		useMessage().success('操作成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

onMounted(() => {
	getAreaList();
	mittBus.on('onHassEvent', (msg) => {
		let jsonObject = JSON.parse(msg);
		let event = jsonObject.event;
		let eventType = event.event_type;
		if (eventType === 'state_changed') {
			let entityId = event.data.new_state.entity_id;
			let state = event.data.new_state.state;
			let isOperate = false;
			for (let i in areaSelectData.value) {
				if (isOperate) {
					break;
				}
				let entities = areaSelectData.value[i].entityList;
				for (let j in entities) {
					if (entities[j].entityId == entityId) {
						entities[j].state = state;
						switch (entities[j].state) {
							case 'on':
								entities[j].switchSate = true;
								break;
							case 'off':
								entities[j].switchSate = false;
								break;
							case 'unavailable':
								entities[j].switchSate = false;
								entities[j].disabled = true;
								break;
						}
						console.log('finded and update entity state', entities[j].entityId);
						isOperate = true;
						break;
					}
				}
			}
		}
	});
});

onUnmounted(() => {
	mittBus.off('onHassEvent', () => {});
});
</script>
<style scoped>
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.text {
	font-size: 14px;
}

.item {
	margin-bottom: 18px;
}

.box-card {
	width: 360px;
	margin: 8px;
}
</style>
